import os
import time
from time import sleep
from config import file_url_config
import pandas as pd
from config.excel_config import column_name

def check_downfile(file_list):
    start_time = time.time()
    while True:
        try:
            file_list2 = os.listdir(file_url_config.download_selenium_excel_file_url)
        except Exception as e:
            sleep(1)
            continue
       # print("下载之前的文件列表: %s" % file_list)
      #  print("下载后的文件列表: %s" % file_list2)
        download_file = list(set(file_list2) - set(file_list))
      #  print("下载后的文件: %s" % download_file)
        if len(download_file) == 0:
           # print("没有文件被下载")
            sleep(1)
            continue
        else:
            if (download_file[0].endswith('csv') | download_file[0].endswith('xlsx') | download_file[0].endswith('xls')
                    | download_file[0].endswith('xlsx.crdownload') | download_file[0].endswith('xls.crdownload')):
                print('下载成功,文件名：%s' % download_file[0])
                return download_file[0]
        end_time = time.time()
        if end_time - start_time > 30:
            print('下载文件失败，重新下载')
            return 'Failed'


def create_file(file_url=''):
    if len(file_url) == 0:
        file_url = file_url_config.download_selenium_excel_file_url
    try:
        # 使用os.makedirs创建文件夹，包括递归创建父文件夹
        os.makedirs(file_url)
        print(f"文件夹 '{file_url}' 创建成功。")
    except FileExistsError:
        print(f"文件夹 '{file_url}' 已经存在。")


def create_empty_total_excel():
    data = {}
    for key, value in column_name.items():
        data[key] = []

    # data = {
    #     column_name['CKSJ']: [],
    #     column_name['PSS']: [],
    #     column_name['PSS_BACP']: [],
    #     column_name['SCCJ']: [],
    #     column_name['YYMC']: [],
    #     column_name['DJ']: [],
    #     column_name['SL']: [],
    #     column_name['PCXX']: []
    # }
    df = pd.DataFrame(data)
    df.to_excel(file_url_config.download_one_day_total_excel_file_url, index=False)


def rename_file_title(source_dir, destination_dir, files, new_filename):
    # 获取源目录下的所有文件
    # files = os.listdir(source_dir)

    if files:

        # 构造完整的文件路径
        source_path = os.path.join(source_dir, files)

        timestamp = int(time.time() * 1000)

        # 构造新文件名的完整路径
        new_file_path = os.path.join(source_dir, new_filename)

        # 使用os.rename重命名文件
        os.rename(source_path, new_file_path)

        # 构造目标文件夹的完整路径
        destination_path = os.path.join(destination_dir, new_filename)

        # 使用shutil.copy2将文件复制到另一个文件夹
     #   shutil.copy2(new_file_path, destination_path)

     #   print(f"文件 '{files}' 改名并成功复制到 '{destination_path}'。")
    else:
        print("源目录下没有文件。")


def delete_file(file_path):
    # 使用os.remove()删除文件
    try:
        os.remove(file_path)
        print(f"文件 '{file_path}' 删除成功")
    except FileNotFoundError:
        print(f"文件 '{file_path}' 不存在")
    except Exception as e:
        print(f"删除文件时发生错误: {e}")


# 失败之后新建一个记事本表示 失败
def scraping_error(file_url, log_msg):
    # 打开一个新文件，如果文件不存在则创建
    with open(file_url, 'w') as file:
        # 向文件写入一行字符串
        file.write(f'{log_msg}\n')


def create_today_dir():

    # 从网页上面直接下载好的文件存放位置
    create_file(file_url_config.download_selenium_excel_file_prefix_url)
    create_file(file_url_config.download_selenium_excel_file_url)

    # 处理过后的文件夹存放位置
    create_file(file_url_config.download_excel_file_prefix_url)
    create_file(file_url_config.download_excel_file_url)

    # 创建当天的汇总表
    delete_file(file_url_config.download_one_day_total_excel_file_url)
    create_empty_total_excel()

    # 检查一下总的汇总表的列数
   # check_total_excel_all_columns()

    # 日志存放位置
    create_file(file_url_config.log_file_prefix_url)
    create_file(file_url_config.log_file_url)


def check_total_excel_all_columns():
    # 读取Excel表格
    df = pd.read_excel(file_url_config.download_total_excel_all_file_url)  # 替换为实际的Excel文件路径

    # 检查并添加缺失的列
    for column_key, column_value in column_name.items():
        if column_value not in df.columns:
            df[column_value] = None  # 在DataFrame中添加缺失的列

    # 将更新后的DataFrame保存回Excel文件
    df.to_excel(file_url_config.download_total_excel_all_file_url, index=False)


if __name__ == '__main__':
    create_today_dir()
